using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using IGlobalist.Cms.Common;
using IGlobalist.Cms.Bll;
using IGlobalist.Cms.Model;
using System.Text;


namespace IGlobalist.Cms.Admin.Control
{
    public partial class PageAddEdit : AdminBaseUserControl
    {
        public event EventHandler SavePage;
        public event EventHandler DeletePage;
        public event EventHandler ViewContent;
        public event EventHandler ViewCategory;


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ddlClassPage.DataBind();
                ddlPage.DataBind();
                //Session[SessionVariable.Clazz.CurrentID] = ddlClassPage.SelectedValue;
                //BindCategories();
            }

        }

        public void DoBindPage(object sender, EventArgs e)
        {
            PageTree ucPageTree = (PageTree)sender;
            long pageID = Convert.ToInt64(ucPageTree.SelectedValue);
            BindPage(pageID);

        }

        protected void BindPage(long pageID)
        {
            IPage page = PageController.GetPageCurrent(pageID);
            hdfPageID.Value = pageID.ToString();
            ucCmsExtPropertiesForm.PropertyList = page.ExtPropertyList;
            ddlPage.DataBind();

            if (ucCmsExtPropertiesForm.PropertyList.Count > 10) fsExt.Visible = true;
            else fsExt.Visible = false;

            //ddlPage.Enabled = false;
            ddlClassPage.Enabled = false;
            ddlPage.SelectedValue = page.ParentID.ToString();
            tbName.Text = page.Name;
            tbOrder.Text = page.Order.ToString();
            tbDescription.Text = page.Description;
            try
            {
                ddlType.SelectedValue = Convert.ToString(page.Type);
                if (page.Hidden == true)
                    cbHidden.Checked = true;
                else
                    cbHidden.Checked = false;
                tbKeyWords.Text = page.KeyWords;
            }
            catch { }
            BindTemplate();
            ViewState["CategoryList"] = page.CategoryList;
            BindCategories();

            try
            {
                ddlTemplate.SelectedValue = page.TemplateID.ToString();
            }
            catch
            {
            }
            if (page.ContentList.Count > 0 ? pnlContent.Visible = true : pnlContent.Visible = false)
                lbtnContent.Text = String.Format("Content list ( {0} )", page.ContentList.Count);
            ViewState["ContentList"] = page.ContentList;
            try
            {
                ddlClassPage.SelectedValue = page.ClassID.ToString();
            }
            catch
            {
            }
            ViewState["Page"] = page;
            lblStatus.Text = "View  Page";
            tbName.Enabled = false;
        }



        public void DoNew(object sender, EventArgs e)
        {
            NewPage();
        }

        public void NewPage()
        {
            ddlClassPage.Enabled = true;
            lblStatus.Text = "Add New Page";
            ddlClassPage.DataBind();
            ddlClassPage.SelectedIndex = 0;
            ICmsClass clazz = ClassController.GetClass(Convert.ToInt64(ddlClassPage.SelectedValue));
            hdfClassID.Value = ddlClassPage.SelectedValue;
            hdfPageID.Value = "0";
            tbDescription.Text = "";
            tbOrder.Text = "";
            tbName.Text = "";
            tbKeyWords.Text = "";
            tbName.Focus();
            cbHidden.Checked = false;
            tvCatPageType.Visible = false;
            tbName.Enabled = true;
            ucCmsExtPropertiesForm.PropertyList = clazz.PropertyList;
            ddlPage.DataBind();
            lblError.Text = "";
            ViewState["CategoryList"] = null;
            BindCategories();
            BindTemplate();
            ViewState["Page"] = null;
            pnlContent.Visible = false;
            if (ucCmsExtPropertiesForm.PropertyList.Count > 10) fsExt.Visible = true;
            else fsExt.Visible = false;
        }

        public void DoSave(object sender, EventArgs e)
        {
            try
            {
                ICmsClass clazz = new CmsClass();
                if (String.IsNullOrEmpty(tbName.Text)) { lblError.Text = "Require Page Name"; return; }
                bool success = false;
                IPage page = new IGlobalist.Cms.Model.Page();
                clazz = ClassController.GetClass(Convert.ToInt64(ddlClassPage.SelectedValue));
                if (ViewState["Page"] != null)
                {
                    tbName.Enabled = false;
                    page = (IPage)ViewState["Page"];
                    page.EditedBy = IGlobalistMembership.GetUser().ID;
                }
                else
                {
                    page.Author = IGlobalistMembership.GetUser().ID;
                    page.Class = clazz;
                    page.ClassID = Convert.ToInt64(ddlClassPage.SelectedValue);
                }

                if (clazz.PropertyList.Count > page.ExtPropertyList.Count)
                {
                    for (int i = 0; i < clazz.PropertyList.Count - page.ExtPropertyList.Count; i++)
                    {
                        page.ExtPropertyList.Add(clazz.PropertyList[page.ExtPropertyList.Count + i]);
                    }
                    PageController.UpdatePage(page);
                }
                //page.ExtPropertyList = ucCmsExtPropertiesForm.PropertyList;
                page.Description = tbDescription.Text;
                page.Name = tbName.Text.Replace(" ", "");
                page.KeyWords = tbKeyWords.Text;
                //page.PageType = Convert.ToInt16(ddlPageType.SelectedValue);
                if (tbOrder.Text.Trim() == "")
                    page.Order = 0;
                else
                    page.Order = Convert.ToInt32(tbOrder.Text);

                if (cbHidden.Checked == true)
                    page.Hidden = true;
                else
                    page.Hidden = false;

                page.Type = Convert.ToInt16(ddlType.SelectedValue);

                IList<long> subList = new List<long>();
                foreach (TreeNode trenode in tvCatPageType.Nodes)
                {
                    foreach (TreeNode childroot in trenode.ChildNodes)
                    {
                        if (childroot.Checked == true)
                        {
                            subList.Add(Convert.ToInt64(childroot.Value));
                        }
                        else
                        {
                            foreach (TreeNode cc in childroot.ChildNodes)
                            {
                                if (cc.Checked == true)
                                {
                                    subList.Add(Convert.ToInt64(cc.Value));
                                }
                            }
                        }
                    }
                }

                page.TemplateID = Convert.ToInt64(ddlTemplate.SelectedValue);
                page.ClassTypeID = Convert.ToInt16(CmsObjectType.Page);
                ContentCategoryList catList = new ContentCategoryList();
                TreeNode node = tvCategory.Nodes[0];
                AddCategory(catList, node);
                page.CategoryList = catList;
                page.ParentID = Convert.ToInt64(ddlPage.SelectedValue);
                bool insert = false;
                if (ViewState["Page"] != null)
                {
                    PageController.UpdatePage(page);
                    success = true;
                    lblStatus.Text = "Update successful";                    
                }
                else
                {
                    if (IsExist(page.Name))
                    {
                        PageController.InsertPage(page);
                        success = true;
                        lblError.Text = "";
                        insert = true;
                    }
                }

                if ((SavePage != null) && (success == true))
                {
                    SavePage(this, new EventArgs());
                    if( insert==true)
                        NewPage();  
                }                
            }
            catch
            {
            }

        }

        protected void AddCategory(ContentCategoryList list, TreeNode node)
        {
            IContentCategory cat = new Category();
            for (int i = 0; i < node.ChildNodes.Count; i++)
            {
                TreeNode nodeChild = node.ChildNodes[i];
                if (nodeChild.Checked == true && nodeChild.Parent.Checked == false)
                {
                    cat = CategoryController.GetCategory(Convert.ToInt64(nodeChild.Value));
                    list.Add(cat);
                }
                AddCategory(list, nodeChild);
            }

        }

        public void DoCopy(object sender, EventArgs e)
        {
            //ViewState["PageID"] = null;
            //tbName.Text = "";
        }

        public void DoDeletePage(object sender, EventArgs e)
        {

            if (ViewState["Page"] != null)
            {
                IPage page = (IPage)ViewState["Page"];
                PageController.DeletePage(page.ID);
            }

            NewPage();

            if (DeletePage != null)
            {
                DeletePage(this, new EventArgs());
            }

        }

        public void DoHidden(object sender, EventArgs e)
        {
            this.Visible = false;
        }

        public void DoShow(object sender, EventArgs e)
        {
            this.Visible = true;
        }

        private void PopulateBind(IContentCategory category, TreeNode node)
        {
            ContentCategoryList list = new ContentCategoryList();
            if (ViewState["CategoryList"] != null)
                list = (ContentCategoryList)ViewState["CategoryList"];

            if (category.CategoryList != null)
                foreach (IContentCategory cat in category.CategoryList)
                {
                    TreeNode subNode = new TreeNode(cat.Name, cat.ID.ToString());
                    foreach (IContentCategory c in list)
                    {
                        if (c.ID == Convert.ToInt64(subNode.Value))
                            subNode.Checked = true;
                    }
                    node.ChildNodes.Add(subNode);
                    PopulateBind(cat, subNode);
                }
        }

        public void BindCategories()
        {
            tvCategory.Nodes.Clear();
            IContentCategory root = CategoryController.GetCategoryTree();
            TreeNode nodeRoot = new TreeNode("Categories", "0");
            nodeRoot.NavigateUrl = "javascript:void(0)";
            PopulateBind(root, nodeRoot);
            tvCategory.Nodes.Add(nodeRoot);
            tvCategory.ExpandAll();
            tvCategory.Nodes[0].ShowCheckBox = false;
            tvCategory.Nodes[0].Checked = false;
        }

        private void PopulateBindCatPageType(IContentCategory category, TreeNode node)
        {
            ContentCategoryList list = new ContentCategoryList();
            if (ViewState["CategoryList"] != null)
                list = (ContentCategoryList)ViewState["CategoryList"];

            if (category.CategoryList != null)
                foreach (IContentCategory cat in category.CategoryList)
                {
                    TreeNode subNode = new TreeNode(cat.Name, cat.ID.ToString());
                    foreach (IContentCategory c in list)
                    {
                        if (c.ID == Convert.ToInt64(subNode.Value))
                            subNode.Checked = true;
                    }
                    node.ChildNodes.Add(subNode);
                    PopulateBindCatPageType(cat, subNode);
                }
        }






        public bool IsExist(string name)
        {
            IList<IPage> listPage = PageController.GetPageListByClass(Convert.ToInt64(ddlClassPage.SelectedValue));
            foreach (IPage p in listPage)
            {
                if (name == p.Name)
                {
                    lblError.Text = "Page name is Exist!";
                    return false;
                }
            }

            if (name == "")
            {
                lblError.Text = "Must enter name!";
                return false;
            }
            return true;
        }

        public void BindTemplate()
        {
            ddlTemplate.Items.Clear();
            IList<ICmsClass> classList = new List<ICmsClass>();
            classList = ClassController.GetClassListByClassTypeID(Convert.ToInt16(CmsObjectType.Template));
            foreach (ICmsClass cmclass in classList)
            {

                IList<IGlobalist.Cms.Model.ITemplate> listTemplate = new List<IGlobalist.Cms.Model.ITemplate>();
                listTemplate = TemplateController.GetTemplateListByClass(cmclass.ID);

                for (int i = 0; i < listTemplate.Count; i++)
                {
                    IGlobalist.Cms.Model.ITemplate t = listTemplate[i];
                    ddlTemplate.Items.Add(new ListItem(t.Name, t.ID.ToString()));
                }
            }
        }

        #region Properties
        public string PageID
        {
            get
            {
                IPage page = (IPage)ViewState["Page"];
                return Convert.ToString(page.ID);
            }
        }
        public ContentList Contents
        {
            get { return (ContentList)ViewState["ContentList"]; }
            set { ViewState["ContentList"] = value; }
        }
        #endregion

        protected void lbtnCategory_Click(object sender, EventArgs e)
        {
            if (ViewCategory != null)
            {

                ViewCategory(this, new EventArgs());
            }

        }

        protected void lbtnContent_Click(object sender, EventArgs e)
        {
            if (ViewContent != null)
            {

                ViewContent(this, new EventArgs());
            }

        }

        protected void ddlClassPage_SelectedIndexChanged(object sender, EventArgs e)
        {
            Session[SessionVariable.Clazz.CurrentID] = ddlClassPage.SelectedValue;
            ICmsClass clazz = ClassController.GetClass(Convert.ToInt64(ddlClassPage.SelectedValue));
            if (clazz != null) ucCmsExtPropertiesForm.PropertyList = clazz.PropertyList;
            if (ucCmsExtPropertiesForm.PropertyList.Count > 10) fsExt.Visible = true;
            else fsExt.Visible = false;
        }
    }
}
